import React, { useState, useEffect } from 'react';
import { Row, Col, Menu, Table, Skeleton, Empty, Divider, Input, Select, Spin, Typography, Button } from 'antd';
import { http } from '../../utils/httpClient';
import './index.less';
import { useNavigate } from 'react-router-dom';

interface ChooseSourceProps {
    onSelect: (id: string) => void;
}

interface TableInfo {
    tableName: string;
    data: any[];
    columns: any[];
}

const ChooseSource: React.FC<ChooseSourceProps> = ({ onSelect }) => {
    const [searchText, setSearchText] = useState('');
    const [dataSource, setDataSource] = useState<TableInfo[]>([]);
    const [selectedTable, setSelectedTable] = useState<string>();
    const [description, setDescription] = useState('');
    const [itemsData, setItemsData] = useState<any[]>([]);
    const [filteredItems, setFilteredItems] = useState<any[]>([]);
    const [selectedKeys, setSelectedKeys] = useState<string[]>([]);
    const [loading, setLoading] = useState(true);
    const [empty, setEmpty] = useState(true);

    // 生成表格列
    const generateColumns = (data: any[]) => {
        if (!data.length) return [];
        const sample = data[0];
        return Object.keys(sample).map(key => ({
            title: <div className="table-header">{key}</div>,
            dataIndex: key,
            key: key,
            width: 200,
            ellipsis: true,
            render: (text: any) => (
                <span className="cell-content" title={typeof text === 'string' ? text : ''}>
                    {text}
                </span>
            )
        }));
    };

    // 处理数据源选择
    const handleMenuSelect = (menu: any) => {
        if(menu?.length === 0) {
            return;
        }
        if(menu?.length > 0) menu = menu[0];
        setSelectedKeys([menu.key]);
        if(menu?.keyPath?.length > 0) {
            let props = menu?.item?.props;
            let object = {
                key: props?.datasource_id,
                label: props?.datasource_name,
                ...props
            }
            onSelect(object);
        } else {
            onSelect(menu)
        }
        setLoading(true);
        http.post(`${window.config.API_BASE_URL}/chatbiv3/ds/desc`, {
            user: 'tiantian',
            source_id: menu.key
        }).then((res: any) => {
            if (res.status_code === '200') {
                setDescription(res.description);

                const tables = res.data.map((table: any) => ({
                    tableName: table.table_name,
                    data: table.data.map((item: any) => ({ ...item, key: item.ID })),
                    columns: generateColumns(table.data)
                }));

                setDataSource(tables);
                setSelectedTable(tables[0] ?.tableName);
                // setEmpty(false);
            }
        }).finally(() => setLoading(false));
    };

    // 处理搜索
    useEffect(() => {
        const filtered = itemsData.filter(item =>
            item.label.toLowerCase().includes(searchText.toLowerCase())
        );
        setFilteredItems(filtered);
    }, [searchText, itemsData]);

    // 初始化加载数据源列表
    useEffect(() => {
        http.post(`${window.config.API_BASE_URL}/chatbiv3/ds/available`, { user: 'tiantian' })
            .then((res: any) => {
                if (res.status_code === '200' && res.details ?.length) {
                    const items = res.details.map((item: any) => ({
                        key: item.datasource_id,
                        label: item.datasource_name,
                        ...item
                    }));
                    setItemsData(items);
                    setFilteredItems(items);
                    if (items.length > 0) {
                        handleMenuSelect(items);
                    }
                } else {
                    setEmpty(false);
                }
            })
            .finally(() => setLoading(false));
    }, []);
    const navigate = useNavigate();
    // 跳转到数据管理页面
    const onClick = () => {
        navigate('/dataManagement');
    };
    return (
        <div className='sourceModal'>
            {empty ? (
                <Spin tip="加载中..." spinning={loading}>
                    <Row gutter={16}>
                        {/* 左侧菜单栏 */}
                        <Col span={6}>
                            <div
                                className='sourceLeft'
                            >
                                <Input.Search
                                    placeholder="搜索数据源"
                                    allowClear
                                    onChange={(e) => setSearchText(e.target.value)}
                                    style={{ marginBottom: 16 }}
                                />
                                <Menu
                                    onClick={(item) => handleMenuSelect(item)}
                                    selectedKeys={selectedKeys}
                                    mode="inline"
                                    items={filteredItems}
                                />
                            </div>
                        </Col>
                        <Col span={1}>
                            <Divider type='vertical' style={{ height: '100%' }} />
                        </Col>
                        {/* 右侧内容区域 */}
                        <Col span={17}>
                            {/* 数据简述 */}
                            <div style={{ marginBottom: 24, marginTop: '-22px' }}>
                                <h3>数据简述</h3>
                                <p>{description || '暂无数据描述'}</p>
                            </div>

                            {/* 数据预览 */}
                            <div>
                                <h3>数据预览</h3>
                                <Select
                                    style={{ width: 240, marginBottom: 16 }}
                                    value={selectedTable}
                                    onChange={setSelectedTable}
                                    options={dataSource.map(t => ({
                                        label: t.tableName,
                                        value: t.tableName
                                    }))}
                                />

                                {selectedTable && dataSource.find(t => t.tableName === selectedTable) && (
                                    <Table
                                        columns={dataSource.find(t => t.tableName === selectedTable) ?.columns || []}
                                        dataSource={dataSource.find(t => t.tableName === selectedTable) ?.data}
                                        bordered
                                        pagination={false}
                                        scroll={{ x: 'max-content', y: 500 }}
                                        rowClassName={(_, index) =>
                                            index % 2 === 0 ? 'even-row' : 'odd-row'
                                        }
                                        sticky
                                    />
                                )}
                            </div>
                        </Col>
                    </Row>
                </Spin>)
                : (
                    <Empty
                        description={
                            <Typography.Text>
                                当前未配置任何数据源，请先<Button type="link" onClick={onClick}>配置数据</Button>
                            </Typography.Text>
                        } />
                )}
        </div>
    );
};

export default ChooseSource;